<template>
  <div>
    <!--个人信息展示-->
    <el-card class="box-card" shadow="always">
      <el-row>

        <!--右卡片-->
        <el-col :span="24">
          <el-card class="right_card_user" shadow="hover">

            <el-descriptions title="个人信息" :column="2" border>

              <template slot="extra">
                <el-button type="primary" @click="changeInformation">编辑个人信息</el-button>
                <el-button type="danger" @click="openChangePassword">修改密码</el-button>
              </template>

              <el-descriptions-item>
                <template slot="label">
                  <i class="el-icon-user"></i>
                  姓名
                </template>
                {{ userList.userName }}
              </el-descriptions-item>

              <el-descriptions-item>
                <template slot="label">
                  <i class="el-icon-orange"></i>
                  性别
                </template>
                <el-tag v-if="userList.sex === 0">男</el-tag>
                <el-tag v-if="userList.sex === 1">女</el-tag>
              </el-descriptions-item>

              <el-descriptions-item>
                <template slot="label">
                  <i class="el-icon-mobile-phone"></i>
                  手机号
                </template>
                {{ userList.telephone }}
              </el-descriptions-item>

              <el-descriptions-item>
                <template slot="label">
                  <i class="el-icon-location-outline"></i>
                  城市
                </template>
                {{ userList.address }}
              </el-descriptions-item>

              <el-descriptions-item>
                <template slot="label">
                  <i class="el-icon-bank-card"></i>
                  银行账号
                </template>
                {{ userList.bankCount }}
              </el-descriptions-item>

              <el-descriptions-item>
                <template slot="label">
                  <i class="el-icon-message"></i>
                  邮箱
                </template>
                {{ userList.email }}
              </el-descriptions-item>

              <el-descriptions-item v-if="userList.identity ===1">
                <template slot="label">
                  <i class="el-icon-postcard"></i>
                  营业执照编号
                </template>
                {{ userList.account }}
              </el-descriptions-item>

            </el-descriptions>
          </el-card>
        </el-col>
      </el-row>

    </el-card>

    <!--修改信息对话框-->
    <div>
      <el-dialog
          title="修改个人信息"
          :visible.sync="changeDialogVisible"
          :close-on-click-modal="false"
          :close-on-press-escape="false"
          :before-close="handleClose"
          width="550px">

        <el-form :model="changeList" :rules="changeRules" ref="refForm" label-width="120px">

          <el-form-item label="邮箱" prop="email">
            <el-input v-model="changeList.email" style="width: 80%"></el-input>
          </el-form-item>

          <el-form-item label="城市" prop="address">
            <el-select v-model="changeList.address" placeholder="所在城市">
              <el-option label="上海" value="上海"></el-option>
              <el-option label="北京" value="北京"></el-option>
              <el-option label="成都" value="成都"></el-option>
              <el-option label="重庆" value="重庆"></el-option>
              <el-option label="郑州" value="郑州"></el-option>
              <el-option label="武汉" value="武汉"></el-option>
              <el-option label="南京" value="南京"></el-option>
              <el-option label="杭州" value="杭州"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="submitChangeInformationForm">提交</el-button>
            <el-button @click="changeDialogVisible = false">取消</el-button>
          </el-form-item>

        </el-form>
      </el-dialog>

    </div>

    <!--修改密码对话框-->
    <el-dialog
        title="修改密码"
        :visible.sync="passwordDialogVisible"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        :before-close="handlePasswordClose"
        width="550px">

      <el-form :model="changePassword" :rules="passwordRules" ref="refPasswordForm" label-width="120px">

        <el-form-item label="新密码" prop="password">
          <el-input type="password" v-model="changePassword.password" autocomplete="off"
                    placeholder="设置密码" style="width: 80%"></el-input>
        </el-form-item>

        <el-form-item label="确认密码" prop="checkPassword">
          <el-input type="password" v-model="changePassword.checkPassword" autocomplete="off"
                    placeholder="确定密码" style="width: 80%"></el-input>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitChangePasswordForm">提交</el-button>
          <el-button @click="handlePasswordClose">取消</el-button>
        </el-form-item>

      </el-form>
    </el-dialog>
  </div>


</template>

<script>
import {getUserInformation} from "@/api/user";
import {getGeneralUserById} from "@/api/general/userGeneral";
import {updatePassword, updatePersonalInformation} from "@/api/personal/personal";

export default {

  name: "UserCenter",

  data() {
    /**
     * validatePass：密码框校验器
     */
    const validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'));
      } else {
        /**
         * 一般来讲，获取DOM元素，需要使用document.querySelector('#input1')方法去获取dom节点，然后再获取input1的值。
         但是使用了ref绑定之后，我们就不需要再获取dom节点了，可以直接在上面的input上绑定input1，然后$refs里面调用就行。
         在JavaScript里面通过this.$refs.input1去调用，这样的做法实际上是访问VUE虚拟出来的DOM，可以有效减少获取/操作DOM节点的性能消耗。
         * <div id="app">
         <input type="text" ref="input1" />
         <button @click="add">添加</button>
         </div>
         * 这里的$refs可以看做是ref的选择器，这个$ref是一个对象，通过key可以获取到其中存放的对象。
         当然了，既然是对象，也可以使用方括号运算符去访问，具体是this.$refs[input1]。
         */
        if (this.changePassword.checkPassword !== '') {
          this.$refs.refPasswordForm.validateField('checkPassword');
        }
        callback();
      }
    };

    /**
     * validatePass2：确认密码框校验器
     */
    const validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.changePassword.password) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };

    return {
      /**
       * 改变个人信息的的对话框
       */
      changeDialogVisible: false,

      /**
       * 改变密码的对话框
       */
      passwordDialogVisible: false,

      /**
       * 个人信息列表
       */
      userList: undefined,

      /**
       * 待改变的个人信息
       */
      changeList: {
        id: '',
        email: '',
        address: '',
      },

      /**
       * 密码信息
       */
      changePassword: {
        id: '',
        password: '',
        checkPassword: '',//检查密码
      },

      /**
       * 修改个人信息验证规则
       */
      changeRules: {
        email: [{required: true, trigger: 'blur', message: '邮箱不能为空'},
          {pattern: /^\w[-\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\.)+[A-Za-z]{2,14}/, message: '请输入正确的邮箱'}],
      },

      /**
       * 密码信息验证规则
       */
      passwordRules: {
        password: [{required: true, validator: validatePass, trigger: 'blur'},
          {min: 6, max: 12, pattern: /^[A-Za-z][A-Za-z0-9_]{5,12}$/, message: '密码为6-12位，且第1位是字母，后面5-11位是字母数字下划线'}],
        checkPassword: [{required: true, validator: validatePass2, trigger: 'blur'}],
      }

    };

  },

  created() {
    this.getGeneralUserById()
  },

  methods: {
    /**
     * 获得用户信息
     */
    getGeneralUserById() {
      const user = eval('(' + getUserInformation() + ')');

      const formData = new FormData();

      formData.append("id", user.id);


      getGeneralUserById(formData).then(res => {
        this.userList = res.user;
      }).catch(() => {
        this.$message.error("用户信息获取失败");
      })
    },

    /**
     * 打开改变个人信息的的对话框
     */
    changeInformation() {
      this.changeList.id = this.userList.id;
      this.changeList.email = this.userList.email;
      this.changeList.address = this.userList.address;

      this.changeDialogVisible = true
    },

    /**
     * 打开改变密码的对话框
     */
    openChangePassword() {
      this.changePassword.id = this.userList.id;
      this.passwordDialogVisible = true;
    },

    /**
     * 提交修改后个人信息
     */
    submitChangeInformationForm() {
      this.$refs.refForm.validate(valid => {
        if (valid) {
          const formData = new FormData();

          formData.append("userId", this.changeList.id);
          formData.append("email", this.changeList.email);
          formData.append("address", this.changeList.address);

          updatePersonalInformation(formData).then(res => {

            if (res.message === 1) {
              this.$message.success("个人信息修改成功");
              this.getGeneralUserById();

              this.changeDialogVisible = false
            }

          }).catch(() => {
            this.$message.error("error");
          })

        }
      })
    },

    /**
     * 提交修改后的个人密码
     */
    submitChangePasswordForm(){
      this.$refs.refPasswordForm.validate(valid => {
        if (valid) {
          const formData = new FormData();

          formData.append("userId", this.changePassword.id);
          formData.append("password", this.changePassword.password);

          updatePassword(formData).then(res=>{
            if(res.message===1){
              this.$message.success("密码修改成功");
              this.getGeneralUserById();

              this.passwordDialogVisible=false;
            }
          }).catch(() => {
            this.$message.error("error");
          })
        }
      })
      this.handlePasswordClose()
    },

    /**
     * 关闭改变个人信息的的对话框
     */
    handleClose() {
      this.changeDialogVisible = false
    },

    /**
     * 关闭改变密码的对话框
     */
    handlePasswordClose() {
      this.passwordDialogVisible = false;
      this.$refs.refPasswordForm.resetFields();
    },
  }
}
</script>

<style scoped>
.box-card {
  width: 90%;
  height: 540px;
  margin: 30px auto;
}

.left_card_user {
  margin-top: 10px;
  height: 480px;
  width: 510px;
}

.right_card_user {
  height: 480px;
  margin-top: 10px;
  margin-right: 20px;
  margin-left: 20px;
}
</style>
